
// 机器人初始JSON数据
const robotsData = [
  {
    id: "dprobot-001",
    name: "配送机器人 R-001",
    type: "delivery",
    status: "online",
    currentStatus: "",
    battery: 0,
    taskProgress: 0,
    completedTasks: 0,
    lastOnline: null,
    error: null
  },
  {
    id: "dlrobot-001",
    name: "配送机器人 R-002",
    type: "delivery",
    status: "online",
    currentStatus: "",
    battery: 0,
    taskProgress: 0,
    completedTasks: 0,
    lastOnline: null,
    error: null
  }
];

// 元素引用
const robotsContainer = document.getElementById('robotsContainer');
const onlineCountEl = document.getElementById('onlineCount');
const totalCountEl = document.getElementById('totalCount');
const deliveryModal = document.getElementById('deliveryModal');
const closeDeliveryModal = document.getElementById('closeDeliveryModal');
const cancelDeliveryModal = document.getElementById('cancelDeliveryBtn');
const confirmDeliveryBtn = document.getElementById('confirmDeliveryBtn');
const deliveryRobotName = document.getElementById('deliveryRobotName');
const deliveryRobotStatus = document.getElementById('deliveryRobotStatus');
const robotIdInput = document.getElementById('robotId');

// 添加机器人相关元素
const addRobotBtn = document.getElementById('addRobotBtn');
const addRobotModal = document.getElementById('addRobotModal');
const closeAddModalBtn = document.getElementById('closeAddModalBtn');
const cancelAddBtn = document.getElementById('cancelAddBtn');
const confirmAddBtn = document.getElementById('confirmAddBtn');
const generateIdBtn = document.getElementById('generateIdBtn');

// 机器人计数器
let robotCounter = 0;
let onlineCounter = 0;

function set_task (robot_id,point_id) {
  fetch('/api/setTask', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      robot_id: robot_id,
      point_id: point_id,  // 前端传递的状态字段
    })
  })
  .then(response => response.json())
  .then(res => console.log('后端响应：', res))
  .catch(err => console.error('请求失败：', err));
}


// 机器人类型文本和图标映射
const typeMap = {
  'delivery': { text: '配送机器人', icon: 'fa-truck' },
  'cleaning': { text: '清洁机器人', icon: 'fa-broom' },
  'security': { text: '安防机器人', icon: 'fa-shield' },
  'service': { text: '服务机器人', icon: 'fa-concierge-bell' }
};

// 状态样式映射
const statusMap = {
  'online': { 
    class: 'robot-online',
    text: '在线',
    bgClass: 'bg-robot-online/10',
    textClass: 'text-robot-online',
    indicatorClass: 'bg-robot-online'
  },
  'idle': { 
    class: 'robot-idle',
    text: '空闲',
    bgClass: 'bg-robot-idle/10',
    textClass: 'text-robot-idle',
    indicatorClass: 'bg-robot-idle'
  },
  'offline': { 
    class: 'robot-offline',
    text: '离线',
    bgClass: 'bg-robot-offline/10',
    textClass: 'text-robot-offline',
    indicatorClass: 'bg-robot-offline'
  }
};

// 从JSON数据加载机器人
function loadRobotsFromJson() {
  robotsContainer.innerHTML = '';
  robotCounter = 0;
  onlineCounter = 0;
  
  robotsData.forEach(robot => {
    // 创建机器人卡片
    const robotCard = createRobotCard(robot);
    robotsContainer.appendChild(robotCard);
    
    // 更新计数器
    robotCounter++;
    if (robot.status === 'online' || robot.status === 'idle') {
      onlineCounter++;
    }
  });
  
  // 更新显示的计数器
  onlineCountEl.textContent = onlineCounter;
  totalCountEl.textContent = robotCounter;
}

// 创建机器人卡片
function createRobotCard(robot) {
  const statusConfig = statusMap[robot.status];
  let extraInfo = '';
  let actionBtn = '';
  
  // 根据机器人类型和状态设置额外信息
  if (robot.type === 'delivery' && robot.status === 'online') {
    extraInfo = `<div>
                  <h4 class="text-sm text-gray-500 mb-1">任务进度</h4>
                  <div class="flex items-center">
                    <div class="w-full bg-gray-200 rounded-full h-2.5 mr-2">
                      <div class="bg-primary h-2.5 rounded-full" style="width: ${robot.taskProgress}%"></div>
                    </div>
                    <span class="text-sm font-medium">${robot.taskProgress}%</span>
                  </div>
                </div>`;
    actionBtn = '<i class="fa fa-cog mr-1"></i> 任务';
  } else if ((robot.type === 'cleaning' || robot.type === 'service') && 
            (robot.status === 'online' || robot.status === 'idle')) {
    extraInfo = `<!-- <div>
                  <h4 class="text-sm text-gray-500 mb-1">今日完成</h4>
                  <p class="font-medium">${robot.completedTasks} 个任务</p>
                </div> -->`;
    actionBtn = '<i class="fa fa-cog mr-1"></i> 任务';
  } else if (robot.status === 'offline') {
    extraInfo = `<div>
                  <h4 class="text-sm text-gray-500 mb-1">最后在线</h4>
                  <p class="font-medium">${robot.lastOnline}</p>
                </div>
                <div>
                  <h4 class="text-sm text-gray-500 mb-1">故障提示</h4>
                  <p class="font-medium text-danger">${robot.error}</p>
                </div>`;
    actionBtn = '<i class="fa fa-refresh mr-1"></i> 重连';
  }
  
  // 创建卡片元素
  const card = document.createElement('div');
  card.className = 'bg-white rounded-xl shadow-sm overflow-hidden card-hover fade-in';
  card.dataset.robotId = robot.id;
  card.dataset.status = robot.status;
  card.dataset.type = robot.type;
  card.innerHTML = `
    <div class="p-5 border-b border-gray-100">
      <div class="flex justify-between items-start">
        <div class="flex items-center">
          <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center mr-3">
            <i class="fa ${typeMap[robot.type].icon} text-primary text-xl"></i>
          </div>
          <div>
            <h3 class="font-semibold">${robot.name}</h3>
            <p class="text-sm text-gray-500">ID: ${robot.id}</p>
          </div>
        </div>
        <span class="px-2 py-1 ${statusConfig.bgClass} ${statusConfig.textClass} text-xs rounded-full">
          <span class="robot-status-indicator ${statusConfig.indicatorClass}"></span>${statusConfig.text}
        </span>
      </div>
    </div>
    <div class="p-5">
      <div class="space-y-4">
        <div>
          <h4 class="text-sm text-gray-500 mb-1">当前状态</h4>
          <p class="font-medium ${robot.status === 'offline' ? 'text-danger' : ''}">${robot.currentStatus}</p>
        </div>
        <div>
        </div>
        ${extraInfo}
      </div>
      
      <div class="mt-5 flex justify-end space-x-2">
        <button class="delete-robot-btn px-3 py-1.5 border border-danger text-danger rounded-lg text-sm hover:bg-danger/10 transition-colors">
          <i class="fa fa-trash mr-1"></i> 删除
        </button>
        <!-- <button class="px-3 py-1.5 border border-gray-300 text-gray-700 rounded-lg text-sm hover:bg-gray-50 transition-colors">
          <i class="fa fa-history mr-1"></i> 历史
        </button> -->
        <button class="task-robot-btn px-3 py-1.5 bg-primary text-white rounded-lg text-sm hover:bg-primary/90 transition-colors ${robot.status === 'offline' ? 'opacity-50 cursor-not-allowed' : ''}">
          ${actionBtn}
        </button>
      </div>
    </div>
  `;
  
  // 绑定任务按钮事件
  const taskBtn = card.querySelector('.task-robot-btn');
  if (robot.status !== 'offline') {
    taskBtn.addEventListener('click', () => openDeliveryModal(robot));
  }
  
  // 绑定删除按钮事件
  const deleteBtn = card.querySelector('.delete-robot-btn');
  deleteBtn.addEventListener('click', function() {
    if (confirm(`确定要删除 ${robot.name} 吗？`)) {
      card.classList.add('fade-out');
      setTimeout(() => {
        card.remove();
        updateRobotCounters();
        // 从数据中移除
        const index = robotsData.findIndex(r => r.id === robot.id);
        if (index !== -1) {
          robotsData.splice(index, 1);
        }
      }, 300);
    }
  });
  
  return card;
}

// 打开配送任务模态框
function openDeliveryModal(robot) {
  deliveryRobotName.textContent = robot.name;
  deliveryRobotStatus.textContent = `状态: ${statusMap[robot.status].text} | 电池: ${robot.battery}%`;
  robotIdInput.value = robot.id;
  document.getElementById('deliveryForm').reset();
  deliveryModal.classList.remove('hidden');
}

// 关闭配送任务模态框
function closeDeliveryModalFunc() {
  deliveryModal.classList.add('hidden');
}

// 提交配送任务
confirmDeliveryBtn.addEventListener('click', () => {
  const robotId = robotIdInput.value;
  const room = document.getElementById('deliveryRoom').value;
  const selectedItems = Array.from(document.querySelectorAll('input[name="items"]:checked')).map(el => el.value);
  
  if (!room) {
    alert('请选择目标房间');
    return;
  }
  
  if (selectedItems.length === 0) {
    alert('请至少选择一种物品');
    return;
  }
  
  // 更新机器人状态
  const robot = robotsData.find(r => r.id === robotId);
  if (robot) {
    robot.status = 'online';
    robot.currentStatus = `配送至 ${room} 室`;
    robot.taskProgress = 30;
    
    const robotCard = document.querySelector(`[data-robot-id="${robotId}"]`);
    if (robotCard) {
      const newCard = createRobotCard(robot);
      robotCard.parentNode.replaceChild(newCard, robotCard);
    }
  }
  set_task(robotId,room)
  
  showNotification(`已成功为 ${deliveryRobotName.textContent} 创建配送任务`, 'success');
  closeDeliveryModalFunc();
});

// 添加机器人相关功能
addRobotBtn.addEventListener('click', () => {
  addRobotModal.classList.remove('hidden');
  document.getElementById('addRobotForm').reset();
});

// 关闭添加机器人模态框
function closeAddModal() {
  addRobotModal.classList.add('hidden');
}

closeAddModalBtn.addEventListener('click', closeAddModal);
cancelAddBtn.addEventListener('click', closeAddModal);

// 点击模态框外部关闭
addRobotModal.addEventListener('click', (e) => {
  if (e.target === addRobotModal) {
    closeAddModal();
  }
});

// 自动生成机器人ID
generateIdBtn.addEventListener('click', () => {
  const robotIdInput = document.getElementById('robotId');
  const year = new Date().getFullYear();
  const newId = `RB${year}${(robotCounter + 1).toString().padStart(3, '0')}`;
  robotIdInput.value = newId;
});

// 确认添加机器人
confirmAddBtn.addEventListener('click', () => {
  const robotName = document.getElementById('robotName').value;
  const robotType = document.getElementById('robotType').value;
  const robotId = document.getElementById('robotId').value;
  const robotStatus = document.getElementById('robotStatus').value;
  
  if (!robotName || !robotType || !robotId || !robotStatus) {
    alert('请填写完整的机器人信息');
    return;
  }
  
  // 检查ID是否已存在
  const idExists = robotsData.some(r => r.id === robotId);
  if (idExists) {
    alert('该设备ID已存在，请使用其他ID');
    return;
  }
  
  // 生成新机器人数据
  let batteryLevel, currentStatus, taskProgress, completedTasks, lastOnline, error;
  
  if (robotStatus === 'online') {
    batteryLevel = Math.floor(Math.random() * 30) + 70;
    currentStatus = '执行任务中';
    taskProgress = Math.floor(Math.random() * 70) + 10;
    completedTasks = Math.floor(Math.random() * 5) + 1;
    lastOnline = null;
    error = null;
  } else if (robotStatus === 'idle') {
    batteryLevel = Math.floor(Math.random() * 30) + 70;
    currentStatus = '等待任务分配';
    taskProgress = 0;
    completedTasks = Math.floor(Math.random() * 5) + 1;
    lastOnline = null;
    error = null;
  } else { // offline
    batteryLevel = Math.floor(Math.random() * 40) + 10;
    currentStatus = '连接中断';
    taskProgress = 0;
    completedTasks = 0;
    lastOnline = new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(',', '');
    error = '通讯模块异常';
  }
  
  // 创建新机器人对象
  const newRobot = {
    id: robotId,
    name: robotName,
    type: robotType,
    status: robotStatus,
    currentStatus: currentStatus,
    battery: batteryLevel,
    taskProgress: taskProgress,
    completedTasks: completedTasks,
    lastOnline: lastOnline,
    error: error
  };
  
  // 添加到数据数组
  robotsData.push(newRobot);
  
  // 创建并添加卡片
  const newRobotCard = createRobotCard(newRobot);
  robotsContainer.appendChild(newRobotCard);
  
  // 更新计数器
  robotCounter++;
  if (robotStatus === 'online' || robotStatus === 'idle') {
    onlineCounter++;
  }
  
  onlineCountEl.textContent = onlineCounter;
  totalCountEl.textContent = robotCounter;
  
  showNotification('机器人添加成功！', 'success');
  closeAddModal();
});

// 更新机器人计数器
function updateRobotCounters() {
  const allRobots = document.querySelectorAll('#robotsContainer > div');
  const onlineRobots = Array.from(allRobots).filter(robot => {
    const status = robot.dataset.status;
    return status === 'online' || status === 'idle';
  });
  
  robotCounter = allRobots.length;
  onlineCounter = onlineRobots.length;
  
  onlineCountEl.textContent = onlineCounter;
  totalCountEl.textContent = robotCounter;
}

// 显示通知提示
function showNotification(message, type = 'info') {
  const notification = document.createElement('div');
  const bgColors = {
    success: 'bg-success',
    info: 'bg-primary',
    error: 'bg-danger'
  };
  
  notification.className = `fixed top-4 right-4 ${bgColors[type]} text-white px-4 py-2 rounded-lg shadow-lg z-50 fade-in`;
  notification.textContent = message;
  document.body.appendChild(notification);
  
  setTimeout(() => {
    notification.style.opacity = '0';
    notification.style.transform = 'translateY(-10px)';
    notification.style.transition = 'opacity 0.3s, transform 0.3s';
    setTimeout(() => notification.remove(), 300);
  }, 3000);
}

// 绑定事件
closeDeliveryModal.addEventListener('click', closeDeliveryModalFunc);
cancelDeliveryModal.addEventListener('click', closeDeliveryModalFunc);

deliveryModal.addEventListener('click', (e) => {
  if (e.target === deliveryModal) {
    closeDeliveryModalFunc();
  }
});

// 更新当前时间
function updateTime() {
  const now = new Date();
  const timeString = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(',', '');
  
  document.getElementById('current-time-robot').textContent = timeString;
}

// 导航菜单切换逻辑
const menuToggle = document.getElementById('menu-toggle');
const sidebar = document.querySelector('aside');
const sidebarOverlay = document.getElementById('sidebar-overlay');

menuToggle.addEventListener('click', () => {
  sidebar.classList.toggle('hidden');
  sidebar.classList.toggle('absolute');
  sidebar.classList.toggle('top-0');
  sidebar.classList.toggle('left-0');
  sidebar.classList.toggle('h-full');
  sidebarOverlay.classList.toggle('hidden');
});

sidebarOverlay.addEventListener('click', () => {
  sidebar.classList.add('hidden');
  sidebarOverlay.classList.add('hidden');
});

// 初始化
loadRobotsFromJson();
updateTime();
setInterval(updateTime, 1000);